<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cates;

class CategoryController extends Controller
{

    /**
     * 获取 分类管理_列表
     * Author: DaXiong
     */
    public function index(){
//        try {
//
//        } catch (\Exception $e) {
//            return $this->returnJson(1, '添加失败');
//        }
        $params = [
            'name' => (string)request('name','')
        ];
        $lists = Cates::where(function($query) use($params){
            if ($params['name']){
                $query->where('name','like','%'.$params['name'].'%');
            }
        })
            ->orderBy('id','DESC')
            ->paginate(10);
        $this->stateToText($lists,[
            'status' => Cates::STATUS_TEXT,
            'option'=> Cates::OPTION_TEXT
        ]);
        return $this->returnJson(0, '',$lists);
    }

    /**
     * 视频管理_分类列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function all(){
        try {
            $list = Cates::where('status',Cates::STATUS_1)->get(['id','name']);
            return $this->returnJson(0, '',$list);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }

    }

    /**
     * 分类管理_新增
     * Author: DaXiong
     */
    public function update(){
        try {
            $data = request()->all();
            if($data['id']){
                //修改
                $info = Cates::find($data['id']);
                if(!$info){
                    return $this->returnJson(1, '数据不存在');
                }
                $info->update($data);
                return $this->returnJson(0, '编辑成功');
            }else{
                //新增
                Cates::create($data);
                return $this->returnJson(0, '添加成功');
            }

        } catch (\Exception $e) {
            return $this->returnJson(1, '添加失败');
        }
    }

    /**
     * 分类管理_删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(){
        try {
            $id = (int)request('id',0);
            if(Cates::destroy($id)){
                return $this->returnJson(0, '删除成功');
            }
            $this->returnJson(1, '删除失败');
        } catch (\Exception $e) {
            return $this->returnJson(1, '删除失败');
        }
    }

}
